﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.UserData;
using System.Device.Location;
using Microsoft.Phone.Tasks;

namespace AVICFEEDSApp
{
	public partial class MainPage : PhoneApplicationPage
	{
		private Contacts _contacts = new Contacts();
		private SaveContactTask _saveContactTask = new SaveContactTask();

		public MainPage()
		{
			InitializeComponent();
			this.Loaded += new RoutedEventHandler(MainPage_Loaded);

			this._contacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(Contacts_SearchCompleted);
			this._saveContactTask.Completed += new EventHandler<SaveContactResult>(SaveContactTask_Completed);
		}

		private void MainPage_Loaded(object sender, RoutedEventArgs e)
		{
			// See if the navigation to this page was due to a search extension
			if (NavigationContext.QueryString.ContainsKey("PlaceName") == true && NavigationContext.QueryString.ContainsKey("PlaceLatitude") == true && NavigationContext.QueryString.ContainsKey("PlaceLongitude") == true)
			{
				double longitude = 0;
				double latitude = 0;
				if (double.TryParse(NavigationContext.QueryString["PlaceLongitude"], out longitude) == true)
				{
					if (double.TryParse(NavigationContext.QueryString["PlaceLatitude"], out latitude) == true)
					{
						Common.SaveContact(this._saveContactTask, NavigationContext.QueryString["PlaceName"], longitude, latitude);
					}
				}
			}
			else
			{
				LoadContacts();
			}
		}

		/// <summary>
		/// Loads contacts on the device that are saved as POIs.
		/// </summary>
		private void LoadContacts()
		{
			this._contacts.SearchAsync("@[", FilterKind.DisplayName, null);
		}

		private void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
		{
			// Fills the Contact list after the search completes
			try
			{
				// Filter contacts that contain a @[
				ContactResultsData.DataContext =
					from Contact contact in e.Results
					select new KeyValuePair<string, string>(contact.DisplayName.Substring(0, contact.DisplayName.IndexOf("@[")), contact.DisplayName);
			}
			catch (System.Exception)
			{
				//No results
			}

			if (ContactResultsData.Items.Count > 0)
			{
				ContactResultsLabel.Visibility = System.Windows.Visibility.Collapsed;
			}
			else
			{
				ContactResultsLabel.Text = "no saved POIs";
			}
		}

		private void SearchButton_Click(object sender, EventArgs e)
		{
			NavigationService.Navigate(new Uri("/AddressSearch.xaml", UriKind.Relative));
		}

		private void SaveContactTask_Completed(object sender, SaveContactResult e)
		{
			// Check if the user tapped the save button
			if (e.TaskResult == TaskResult.OK)
			{
				MessageBox.Show("You may need to refresh contacts via Bluetooth on the Pioneer navigation system.  Press your phone's back button to return to search results.", "Contact saved as POI", MessageBoxButton.OK);
			}

			// Reload the POIs in the contact list
			LoadContacts();
		}
	}
}